package com.zlp.security.service;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zlp.entity.Permission;
import com.zlp.entity.User;
import com.zlp.security.dto.MyUserDetails;
import com.zlp.service.PermissionService;
import com.zlp.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service("userDetailsService")
@Slf4j(topic = "MyDetailsServiceImpl")
public class MyDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Resource
    private PermissionService permissionService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        log.info("loadUserByUsername.req username={}",username);
        //  1. 查询用户
        User user = userService.loadUserByUsername(username);
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("User [" + username + "] was not found in db");
        }
        // 2. 设置角色
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        List<Permission> permissionList = permissionService.getPermissionList(user.getId());
        if (CollectionUtil.isNotEmpty(permissionList)) {
            grantedAuthorities = permissionList.stream()
                    .filter(permission -> StringUtils.isNotBlank(permission.getPermissionValue()))
                    .map(permission ->new SimpleGrantedAuthority(permission.getPermissionValue()))
                    .collect(Collectors.toList());
        }
        // 赋值到 MyUserDetails
        return new MyUserDetails(user,CollectionUtil.isEmpty(grantedAuthorities)
                ? Collections.emptyList() : grantedAuthorities);
    }

}
